package com.lovo.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lovo.bean.UserInfoBean;
import com.lovo.result.GlobalHandleException;
import com.lovo.result.Result;
import com.lovo.service.IUserInfoService;

import javax.servlet.ServletResponse;
import java.io.IOException;

public class WebUtil {
    public static String SERVER_NAME = "";
    public static void writeValueAsString(ServletResponse response, Result result) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(mapper.writeValueAsString(result));
    }
    public static UserInfoBean verifyToken(String token, IUserInfoService userInfoService) throws IOException {
        if(token == null){
            return null;
        }
        String userName = null;
        try {
            userName = JWTUtil.getAudience(token);
        } catch (GlobalHandleException e) {
            return null;
        }
        UserInfoBean userInfoBean = userInfoService.selectByUserName(userName);
        if(userInfoBean == null){
            return null;
        }
        try {
            JWTUtil.verifyToken(token,userInfoBean.getUserPass());
        } catch (GlobalHandleException e) {
            return null;
        }

        return userInfoBean;
    }
}
